package logic

import (
	"context"
	"errors"
	"wei/cache"
	"wei/models/mysql"

	"wei/weirpc/internal/svc"
	"wei/weirpc/weirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *weirpc.LoginRequest) (*weirpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendCode"+in.Account).Result()
	if result != in.SendCode {
		return nil, errors.New("短信验证码错误")
	}
	s, _ := cache.Rdb.Get(l.ctx, "captchaCode").Result()
	if s != in.CaptchaCode {
		return nil, errors.New("图形验证码错误")
	}
	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account)
	if in.Account != user.Account {
		return nil, errors.New("用户不存在")
	}

	if in.Password != user.Password {
		return nil, errors.New("密码错误")
	}

	return &weirpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
